import { devMode, baseURL } from "@/config";

export default {};

// 图片预览
export const previewOne = url => {
  if (!url) return false;
  uni.previewImage({
    current: url,
    urls: [url]
  });
};

export const toast = content => {
  uni.showToast({
    title: content,
    duration: 1500,
    icon: "none"
  });
};

export const showModal = options => {
  uni.showModal(
    Object.assign({}, options, {
      confirmColor: "#3B4B8E"
    })
  );
};

export function showLoading() {
  uni.showLoading({
    title: "请稍等",
    mask: true
  });
}

export function hideLoading() {
  uni.hideLoading();
}

// 深拷贝
export const deepClone = json => {
  return JSON.parse(JSON.stringify(json));
};

/**
 * 日志输出
 */
export const log = info => {
  if (devMode) {
    console.log(info);
  }
};


export const getImgUrl = url => {
  if (url) {
    if (url.indexOf("http") >= 0) {
      return url;
    } else if (url.indexOf("/") == 0) {
      return baseURL + url;
    } else {
      return baseURL + "/" + url;
    }
  } else {
    return "/static/common/head.png";
  }
};


/* 获取后缀名 */
export const getFileExt = fileName => {
  if (!fileName) return "";
  return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length);
};

// 对所有输入项去除前后空格
export const getTrimParams = src => {
  let params = JSON.parse(JSON.stringify(src));
  if (!params) return params;
  if (typeof params === "object") {
    let resp = JSON.parse(JSON.stringify(params));
    for (let key in resp) {
      if (resp[key] && typeof resp[key] === "string") {
        resp[key] = resp[key].trim();
      }
    }
    return resp;
  } else if (params) {
    return params.trim();
  }
};

// 成功或失败方法
export const resultHandler = (title, callback, isSuccess = false) => {
  uni.showToast({
    title,
    duration: 1500,
    icon: isSuccess ? "success" : "none",
    mask: true
  });
  if (callback) {
    let t = setTimeout(() => {
      callback();
      clearTimeout(t);
    }, 1500);
  }
};

// 校验
export const verifyParams = (condition, errMsg) => {
  if (condition) {
    return true;
  } else {
    throw errMsg;
  }
};

/* *
 * 根据服务器返回的pageData
 * 拼接list数据
 */
export const loadPage = {
  finished(res) {
    return res.lastPage;
  },
  getList(res, list) {
    // 设置数据
    if (res.pageNumber === 1) {
      return res.list;
    } else {
      return list.concat(res.list);
    }
  },
  isNone(res) {
    return res.totalRow <= 0;
  }
};

// 非空
export const isNotBlank = val => {
  return val !== undefined && val !== null && val !== "";
};

// 检查版本更新
export const versionUpdateCheck = () => {
  // #ifdef APP-PLUS || MP-WEIXIN || MP-BAIDU || MP-ALIPAY
  if (uni.canIUse("getUpdateManager")) {
    const updateManager = uni.getUpdateManager();

    updateManager.onCheckForUpdate(function(res) {
      // 请求完新版本信息的回调
      // console.log('新版本信息的回调:', res.hasUpdate);
    });

    updateManager.onUpdateReady(function(res) {
      showModal({
        title: "更新提示",
        content: "新版本已经准备好，是否重启应用？",
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate();
          }
        }
      });
    });

    updateManager.onUpdateFailed(function(res) {
      // 新的版本下载失败
    });
  }
  // #endif
};

export function getUrlVars(url) {
  url = decodeURIComponent(url);
  let hash,
    myJson = {};
  let hashes = url.split(";");
  if (hashes) {
    for (let i = 0; i < hashes.length; i++) {
      hash = hashes[i].split("=");
      myJson[hash[0]] = hash[1];
    }
  }
  return myJson;
}


/** 超过长度返回省略号 */
export function wordEllipsis(str, len) {
  if (!str) return "";
  if (str.length * 2 <= len) {
    return str;
  }
  let strlen = 0;
  let s = "";
  for (let i = 0; i < str.length; i++) {
    s = s + str.charAt(i);
    if (str.charCodeAt(i) > 128) {
      strlen = strlen + 2;
    } else {
      strlen = strlen + 1;
    }
    if (strlen > len) {
      return s.substring(0, s.length - 1) + "...";
    }
  }
  return str;
}

//保存文件到本地
export function saveFileToLocal(tempFilePath) {
  const savePoster = () => {
    uni.showLoading({
      title: "正在保存...",
      mask: true
    });
    uni.saveImageToPhotosAlbum({
      filePath: tempFilePath,
      success() {
        uni.hideLoading();
        uni.showToast({
          title: "图片已保存",
          icon: "success"
        });
      },
      fail() {
        uni.hideLoading();
      }
    });
  };
  uni.getSetting({
    success(res) {
      if (!res.authSetting["scope.writePhotosAlbum"]) {
        uni.authorize({
          scope: "scope.writePhotosAlbum",
          success() {
            savePoster();
          },
          fail() {
            showModal({
              title: "温馨提示",
              content: "你关闭了访问相册的权限，无法保存，请允许访问相册",
              showCancel: false
            });
          }
        });
      } else {
        savePoster();
      }
    }
  });
}

/**
 * @returns 随机生成文件名
 */
export function createPicKey() {
  var now = new Date();
  var year = now.getFullYear(); //得到年份
  var month = now.getMonth(); //得到月份
  var date = now.getDate(); //得到日期
  var hour = now.getHours(); //得到小时
  var minu = now.getMinutes(); //得到分钟
  month = month + 1;
  if (month < 10) month = "0" + month;
  if (date < 10) date = "0" + date;
  var number = now.getSeconds() % 43; //这将产生一个基于目前时间的0到42的整数。
  var time = year + month + date + hour + minu;
  return time + "_" + number;
}
